using hao_Dto;
using hao_Model;
using hao_Reppsitory.Product;
using hao_Common.AutoMapper.Services;
using hao_Common.Consul.Services;
using hao_Common.Http.Interfaces;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace Product.Service
{
    public class ProductService : IProductService
    {
        private readonly IProductRepository _productRepository;
        private readonly IProductImageRepository _productImageRepository;
        private readonly IMapperService _mapperService;
        private readonly IServiceDiscovery _serviceDiscovery;
        private readonly IHttpHelper _httpHelper;
        private readonly ILogger<ProductService> _logger;

        public ProductService(
            IProductRepository productRepository, 
            IProductImageRepository productImageRepository,
            IMapperService mapperService,
            IServiceDiscovery serviceDiscovery,
            IHttpHelper httpHelper,
            ILogger<ProductService> logger)
        {
            _productRepository = productRepository;
            _productImageRepository = productImageRepository;
            _mapperService = mapperService;
            _serviceDiscovery = serviceDiscovery;
            _httpHelper = httpHelper;
            _logger = logger;
        }

        public async Task<Guid> SaveProductAsync(ProductPublishDto dto)
        {
            if (dto.Id.HasValue && dto.Id.Value != Guid.Empty)
            {
                // 更新商品
                var success = await UpdateProductAsync(dto.Id.Value, dto);
                return success ? dto.Id.Value : Guid.Empty;
            }
            else
            {
                // 新增商品
                return await AddProductAsync(dto);
            }
        }

        public async Task<Guid> AddProductAsync(ProductPublishDto dto)
        {
            // 调用带用户ID的方法，传入空的用户ID
            return await AddProductAsync(dto, Guid.Empty);
        }
        
        public async Task<Guid> AddProductAsync(ProductPublishDto dto, Guid userId)
        {
            var product = _mapperService.Map<hao_Model.Product>(dto);
            if (!dto.Id.HasValue || dto.Id.Value == Guid.Empty)
            {
                product.Id = Guid.NewGuid();
            }
            product.CreatedAt = DateTime.UtcNow;
            
            // 设置用户ID
            product.UserId = userId;

            var productImages = dto.ImageUrls?.Select(url => 
            {
                var image = _mapperService.Map<ProductImage>(url);
                image.Id = Guid.NewGuid();
                image.ProductId = product.Id;
                return image;
            }).ToList() ?? new List<ProductImage>();

            await _productRepository.AddAsync(product);
            foreach (var img in productImages)
            {
                await _productImageRepository.AddAsync(img);
            }
            return product.Id;
        }

        public async Task<ProductResponseDto> GetProductByIdAsync(Guid id)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null || product.IsDeleted)
                return null;

            var productDto = _mapperService.Map<ProductResponseDto>(product);
            
            // 获取商品图片
            var images = await GetProductImagesAsync(id);
            productDto.ImageUrls = _mapperService.MapList<ProductImage, string>(images);
            
            // 获取卖家信息
            await FillSellerInfoAsync(productDto);

            return productDto;
        }
        
        /// <summary>
        /// 填充卖家信息
        /// </summary>
        /// <param name="productDto">商品DTO</param>
        private async Task FillSellerInfoAsync(ProductResponseDto productDto)
        {
            if (productDto == null || productDto.UserId == Guid.Empty)
                return;
                
            try
            {
                // 通过服务发现获取用户服务URL
                var userServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("user-service");
                if (string.IsNullOrEmpty(userServiceUrl))
                {
                    _logger.LogWarning("无法获取用户服务URL");
                    return;
                }
                
                // 调用用户服务API获取卖家信息
                var userApiUrl = $"{userServiceUrl}/api/users/{productDto.UserId}";
                //var response = await _httpHelper.GetAsync(userApiUrl);
                
                //if (string.IsNullOrEmpty(response))
                //{
                //    _logger.LogWarning($"获取用户信息失败，用户ID: {productDto.UserId}");
                //    return;
                //}
                
                //// 解析用户信息
                //var userResponse = JsonSerializer.Deserialize<dynamic>(response);
                //if (userResponse != null && userResponse.GetProperty("data").ValueKind != JsonValueKind.Null)
                //{
                //    var userData = userResponse.GetProperty("data");
                    
                //    // 填充卖家信息
                //    if (userData.TryGetProperty("userName", out var userName))
                //        productDto.SellerName = userName.GetString();
                        
                //    if (userData.TryGetProperty("avatar", out var avatar))
                //        productDto.SellerAvatar = avatar.GetString();
                        
                //    if (userData.TryGetProperty("phone", out var phone))
                //        productDto.SellerPhone = phone.GetString();
                        
                //    if (userData.TryGetProperty("email", out var email))
                //        productDto.SellerEmail = email.GetString();
                //}
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取卖家信息时发生错误，卖家ID: {productDto.UserId}");
            }
        }

        public async Task<(List<ProductListDto> products, int total)> GetProductsAsync(int page, int pageSize, string category = null, string keyword = null)
        {
            var allProducts = await _productRepository.GetAllAsync();
            var query = allProducts.Where(p => !p.IsDeleted);

            // 按分类筛选
            if (!string.IsNullOrEmpty(category)) query = query.Where(p => p.Category.Contains(category));
            

            // 按关键词搜索
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(p => p.Title.Contains(keyword) || p.Description.Contains(keyword));
            }

            var total = query.Count();
            var products = query.OrderByDescending(p => p.CreatedAt).Skip((page - 1) * pageSize).Take(pageSize).ToList();

            var productDtos = _mapperService.MapList<hao_Model.Product, ProductListDto>(products);
            
            // 为每个商品设置封面图片
            foreach (var productDto in productDtos)
            {
                var images = await GetProductImagesAsync(productDto.Id);
                productDto.FirstImageUrl = images.FirstOrDefault()?.Url;
            }

            return (productDtos, total);
        }

        public async Task<bool> UpdateProductAsync(Guid id, ProductPublishDto dto)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null || product.IsDeleted)
                return false;

            // 保存原有的创建时间
            var originalCreatedAt = product.CreatedAt;
            
            // 使用AutoMapper更新产品信息
            _mapperService.Map(dto, product);
            
            // 确保ID和创建时间不被覆盖
            product.Id = id;
            product.CreatedAt = originalCreatedAt;

            await _productRepository.UpdateAsync(product);

            // 更新商品图片
            if (dto.ImageUrls != null)
            {
                // 删除旧图片
                var oldImages = await GetProductImagesAsync(id);
                foreach (var oldImg in oldImages)
                {
                    await _productImageRepository.DeleteAsync(oldImg.Id);
                }

                // 添加新图片
                var newImages = dto.ImageUrls.Select(url => 
                {
                    var image = _mapperService.Map<ProductImage>(url);
                    image.Id = Guid.NewGuid();
                    image.ProductId = id;
                    return image;
                }).ToList();

                foreach (var img in newImages)
                {
                    await _productImageRepository.AddAsync(img);
                }
            }

            return true;
        }

        public async Task<bool> DeleteProductAsync(Guid id)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null)
                return false;

            await _productRepository.DeleteAsync(id);
            return true;
        }

        public async Task<List<ProductListDto>> GetProductsByUserIdAsync(Guid userId)
        {
            var allProducts = await _productRepository.GetAllAsync();
            var userProducts = allProducts.Where(p => !p.IsDeleted).ToList();
            
            var productDtos = _mapperService.MapList<hao_Model.Product, ProductListDto>(userProducts);
            
            // 为每个商品设置封面图片
            foreach (var productDto in productDtos)
            {
                var images = await GetProductImagesAsync(productDto.Id);
                productDto.FirstImageUrl = images.FirstOrDefault()?.Url;
            }
            
            return productDtos;
        }

        public async Task<List<ProductImage>> GetProductImagesAsync(Guid productId)
        {
            var allImages = await _productImageRepository.GetAllAsync();
            return allImages.Where(img => img.ProductId == productId && !img.IsDeleted).ToList();
        }
        


        public async Task<(List<ProductListDto> products, int total)> SearchProductsAsync(string keyword, int page, int pageSize)
        {
            return await GetProductsAsync(page, pageSize, null, keyword);
        }
    }
}
